<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">




<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/zhu/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/zhu/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/zhu/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/zhu/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/zhu/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/zhu/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/zhu/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="jwt," />










<meta name="description" content="1.什么是JWT 单点登录SSO jwt  (json web token)                   学习思想，不是API oautht2.0 开发协议">
<meta property="og:type" content="article">
<meta property="og:title" content="jwt">
<meta property="og:url" content="https://gitee-zct.gitee.io/zhu/2021-04-21/1.%E4%BB%80%E4%B9%88%E6%98%AFJWT/index.html">
<meta property="og:site_name" content="zhu">
<meta property="og:description" content="1.什么是JWT 单点登录SSO jwt  (json web token)                   学习思想，不是API oautht2.0 开发协议">
<meta property="og:locale">
<meta property="article:published_time" content="2021-04-21T15:53:46.661Z">
<meta property="article:modified_time" content="2021-04-21T15:54:51.956Z">
<meta property="article:author" content="zhu">
<meta property="article:tag" content="jwt">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee-zct.gitee.io/zhu/2021-04-21/1.什么是JWT/"/>





  <title>jwt | zhu</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/zhu/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhu</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">我的小世界</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/zhu/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/zhu/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/zhu/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/zhu/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/zhu/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/zhu/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://gitee-zct.gitee.io/zhu/zhu/2021-04-21/1.%E4%BB%80%E4%B9%88%E6%98%AFJWT/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/zhu/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhu">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">jwt</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-04-21T23:53:46+08:00">
                2021-04-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/zhu/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index">
                    <span itemprop="name">学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1-什么是JWT"><a href="#1-什么是JWT" class="headerlink" title="1.什么是JWT"></a>1.什么是JWT</h1><blockquote>
<p>单点登录SSO</p>
<p>jwt  (json web token)                   学习思想，不是API</p>
<p>oautht2.0 开发协议</p>
</blockquote>
<hr>
<span id="more"></span>

<blockquote>
<p>**token : 临时 且 唯一 **          缓存有效期机制</p>
<p>有 <strong>有效期</strong> 的 <strong>临时密码</strong></p>
<p>Token 如何生成：UUID作为 token</p>
<p>比如:生成token ,作为rediskey放入redis中，Redis的key作为有效期</p>
<p>传统项目使用session,  缺陷：放在服务器里，不共享，废内存，和项目的内存在一块，没有解耦</p>
<p>session类似redis存放缓存内容</p>
<hr>
<p><strong>大项目都是使用token替代session</strong>,token存redis里</p>
<p>举例：前后端分离项目，用户登录</p>
<p>验证账号密码-&gt;生成对应token<font color='orange'>-&gt;</font>uuid生成token<font color='orange'>-&gt;</font>将该token缓存到redis中<font color='orange'>-&gt;</font>返回token给客户端<font color='orange'>-&gt;</font>客户端保存token在cookie</p>
<p>redisKey=token,value=userid</p>
<hr>
<p>查询的情况下：</p>
<ol>
<li>客户端每次请求在请求头传递该token,</li>
<li>服务器接受到token,从redis中查询key对应的value userid</li>
<li>根据查询的信息返回给客户端</li>
</ol>
<p>使用token的情况下，必须依赖于服务器端：Redis。在高并发情况下，客户端每次传token查询，请求大，频繁调用，对redis压力大。</p>
<p><font color='orange'>Token优点：</font></p>
<ol>
<li>隐藏参数真实性，保证安全。                  直接传递userid非常不好，不安全。low~</li>
<li>临时且唯一，比较安全</li>
</ol>
<p><font color='orange'>缺点：</font></p>
<ol>
<li>依赖服务的，频繁查询，对redis压力大</li>
</ol>
</blockquote>
<hr>
<blockquote>
<p><font color='orange'>JWT  实际上和  Token  设计思想一样</font></p>
<p>jwt ： Java web token</p>
<p>json: 数据的交换格式   轻量级 ,跨语言，减少宽带，可读性高。</p>
<p>Token : </p>
</blockquote>
<p>加密算法：</p>
<p>​    单向加密：MD5    不可逆，只能保留破解，加个盐值</p>
<p>​    双向加密:(对称加密):aes des</p>
<p>​    非对称加密：rsa</p>
<p><font color='cornflowerblue'>HS256表示 MD5单向加密</font></p>
<p>例子：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--        jwt--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.jsonwebtoken<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jjwt<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.6.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">public class JWTTest &#123;</span><br><span class="line">    //前面key,不一定是密钥,密钥是可以加密解密的</span><br><span class="line">    private static String SIGN_KEY =&quot;zhucSignKey&quot;;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        JwtBuilder jwtBuilder= Jwts.builder()</span><br><span class="line">                .claim(&quot;phone&quot;,&quot;15346*53262&quot;)</span><br><span class="line">                //设置签名值,盐值</span><br><span class="line">                .signWith(SignatureAlgorithm.HS256,SIGN_KEY);</span><br><span class="line"></span><br><span class="line">        System.out.println(jwtBuilder.compact());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">---</span><br><span class="line">输出：</span><br><span class="line">eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjE1MzQ2KjUzMjYyIn0.8yPTQMYCYYRg79W7oAU4kDNxySvxluobfHtinmM5KKI</span><br></pre></td></tr></table></figure>

<p>jwt三部分；</p>
<p>  (不加密)第一部分：header  头部 标记什么算法 HS256,RSA256，看是对称还是非对称加密</p>
<p>（不加密）第二部分PayLoad(载荷)，说白了就是，jwt存放的数据，一定是json格式存放</p>
<p>​                注意不能存放敏感数据，比如userid，手机号，用户图片，不安全，直接被base64解码知道了。</p>
<p>（加密）第三部的:PayLoad采用MD5加密之后的签名值</p>
<blockquote>
<p>JWt生成：</p>
<p>​            第一二部分：Base64Encode(header).Base64.Encode(PayLoad).签名值</p>
<p>​                                base64是编码格式（64字符表示二进制），只是把它转换为这个格式，不是加密</p>
<p>​            第三部分加了盐值，不知道盐值不能解码的。其他部分jwt.io可以直接解码</p>
</blockquote>
<p><font color='pink'>第三部分验证成功才保留获取的payload数据，否则签名无效，防止被伪造，因为SiGN_KEY是保存在服务器的</font></p>
<h1 id="如何手写JWT"><a href="#如何手写JWT" class="headerlink" title="如何手写JWT"></a>如何手写JWT</h1><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.example;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSONObject;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.DigestUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Base64;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestJwt</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String SIGN_KEY =<span class="string">&quot;zhuSignKey&quot;</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//head/load/sign</span></span><br><span class="line">        JSONObject header=<span class="keyword">new</span> JSONObject();</span><br><span class="line">        header.put(<span class="string">&quot;alg&quot;</span>,<span class="string">&quot;HS256&quot;</span>);</span><br><span class="line">        <span class="comment">//payload</span></span><br><span class="line">        JSONObject payload=<span class="keyword">new</span> JSONObject();</span><br><span class="line">        payload.put(<span class="string">&quot;phone&quot;</span>,<span class="string">&quot;15346*53262&quot;</span>);</span><br><span class="line">             payload.put(<span class="string">&quot;time&quot;</span>,<span class="number">60</span>);<span class="comment">//60秒过期</span></span><br><span class="line">        String payloadStr=payload.toJSONString();</span><br><span class="line">        <span class="comment">//sign第三部分,payload  Md5加密</span></span><br><span class="line">        String sign= DigestUtils.md5DigestAsHex((payloadStr+SIGN_KEY).getBytes());</span><br><span class="line"></span><br><span class="line">        String jwt= Base64.getEncoder().encodeToString(header.toJSONString().getBytes())+<span class="string">&quot;.&quot;</span>+</span><br><span class="line">                Base64.getEncoder().encodeToString(payloadStr.getBytes())+<span class="string">&quot;.&quot;</span>+sign;</span><br><span class="line">        System.out.println(jwt);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">       <span class="comment">//jwt解密</span></span><br><span class="line">        String[] split = jwt.split(<span class="string">&quot;\\.&quot;</span>);</span><br><span class="line">        String payLoad=<span class="keyword">new</span> String(Base64.getDecoder().decode(split[<span class="number">1</span>].getBytes()));</span><br><span class="line">        System.out.println(payLoad);</span><br><span class="line">        <span class="keyword">boolean</span> b= DigestUtils.md5DigestAsHex((payLoad+SIGN_KEY).getBytes()).equals(split[<span class="number">2</span>]);</span><br><span class="line">       <span class="keyword">if</span>(b==<span class="keyword">true</span>)&#123;</span><br><span class="line">           System.out.println(<span class="string">&quot;cg &quot;</span>);</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h1 id="JWT与Token区别"><a href="#JWT与Token区别" class="headerlink" title="JWT与Token区别"></a>JWT与Token区别</h1><hr>
<ol>
<li>token存在Redis,</li>
<li>jwt对应的payLoad存放在  客户端，</li>
</ol>
<h2 id="JWT优点"><a href="#JWT优点" class="headerlink" title="JWT优点"></a>JWT优点</h2><ol>
<li>减轻服务端的压力</li>
<li>查询效率比token高，不用去查redis，服务端收到验证参数正确就直接用payload了</li>
<li>不容易被客户端篡改数据</li>
</ol>
<p>缺点：</p>
<ol>
<li>如果一旦生成好一个jwt，无法销毁，很难做注销，别人一旦知道</li>
<li>如果jwt payload数据多，相比token占用服务器的带宽资源</li>
</ol>
<p>最好建议在jwt payload数据中，加入一个时间戳，jwt一定要设置一个有效期，j建议时间值短一点。</p>
<hr>
<p>退出登录时，如果不使JWT Token失效会产生如下2个问题</p>
<p>问题1-未过期的token还是可以用</p>
<p>要是用户在多个设备登录了，而且本地保存了token。当一个地方丢弃token，但是这个token要是没有过期，那之前token还是可以用的。</p>
<p>问题2-多个设备会出现死循环</p>
<p>如果我把token存到数据库，当用户退出登录或者修改密码，更新token。当用户下次拿着之前的token来认证时，找到该用户数据库存的token，两个对比一下，如果一样就通过，否则让用户登录。有一个问题，如果这样做，要是有两设备，就死循环了。一个设备登录了，token就会变，导致另一个去登录，然后这个token又失效了，成死循环了。</p>
<p>解决</p>
<p>其实要完美地失效JWT是没办法做到的。</p>
<p>“Actually, JWT serves a different purpose than a session and it is not possible to forcefully delete or invalidate an existing token.”</p>
<p>这篇文章写得比较简单易懂：<a target="_blank" rel="noopener" href="https://medium.com/devgorilla">https://medium.com/devgorilla</a>…</p>
<p>有以下几个方法可以做到失效 JWT token：</p>
<p>将 token 存入 DB(如 Redis)中，失效则删除；但增加了一个每次校验时候都要先从 DB 中查询 token 是否存在的步骤，而且违背了 JWT 的无状态原则(这不就和 session 一样了么？)。</p>
<p>维护一个 token 黑名单，失效则加入黑名单中。</p>
<p>在 JWT 中增加一个版本号字段，失效则改变该版本号。</p>
<p>在服务端设置加密的 key 时，为每个用户生成唯一的 key，失效则改变该 key。<br>————————————————<br>版权声明：本文为CSDN博主「weixin_39634997」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。<br>原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_39634997/article/details/111522444">https://blog.csdn.net/weixin_39634997/article/details/111522444</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/zhu/tags/jwt/" rel="tag"># jwt</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/zhu/2021-04-18/redis(2)/" rel="next" title="redis(2)">
                <i class="fa fa-chevron-left"></i> redis(2)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/zhu/2021-08-05/abc/" rel="prev" title="abc">
                abc <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/zhu/archives/">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/zhu/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/zhu/tags/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFJWT"><span class="nav-number">1.</span> <span class="nav-text">1.什么是JWT</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E6%89%8B%E5%86%99JWT"><span class="nav-number">2.</span> <span class="nav-text">如何手写JWT</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JWT%E4%B8%8EToken%E5%8C%BA%E5%88%AB"><span class="nav-number">3.</span> <span class="nav-text">JWT与Token区别</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JWT%E4%BC%98%E7%82%B9"><span class="nav-number">3.1.</span> <span class="nav-text">JWT优点</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhu</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">25.1k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





        
<div class="busuanzi-count">
 
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


  
    <span class="site-uv">
      踩过的小伙伴
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      本站访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/zhu/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/zhu/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/zhu/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/zhu/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/zhu/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/zhu/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/zhu/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/zhu/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/zhu/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
